package com.sikadwafastdaisfondturbo.pretloan.ui.credit.page

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.sikadwa.lib_permission.OnPermissionCallback
import com.sikadwa.lib_permission.XXPermissions
import com.sikadwafastdaisfondturbo.pretloan.adapter.AmountAdapter
import com.sikadwafastdaisfondturbo.pretloan.analysis.TestDataLibInvoke
import com.sikadwafastdaisfondturbo.pretloan.databinding.PageLimitBinding
import com.sikadwafastdaisfondturbo.pretloan.pro.ProFragment
import com.sikadwafastdaisfondturbo.pretloan.ui.credit.activity.ApplyActivity
import com.sikadwafastdaisfondturbo.pretloan.ui.process.activity.ProcessActivity
import com.sikadwafastdaisfondturbo.pretloan.utils.BarUtils
import com.sikadwafastdaisfondturbo.pretloan.utils.DensityUtils
import com.sikadwafastdaisfondturbo.pretloan.utils.config.Configs
import com.sikadwafastdaisfondturbo.pretloan.utils.event.EventType
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls.addCommonParams
import com.sikadwafastdaisfondturbo.pretloan.utils.http.IHttpCallback
import com.sikadwafastdaisfondturbo.pretloan.utils.rv.LinearDecoration
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/22 17:44
 * @Annotation：贷款额度
 */
class LimitPage(): ProFragment() {
    lateinit var binding: PageLimitBinding
    var isComplete = false

    private var mAmountAdapter: AmountAdapter? = null
    //所有权限
    private var mPermissions: ArrayList<String>? = null
    override fun getRootView(inflater: LayoutInflater): View {
        binding = PageLimitBinding.inflate(inflater)
        return binding.root
    }

    constructor(isComplete: Boolean): this(){
        this.isComplete = isComplete
    }

    override fun initView() {
        binding.parentLayout.setPadding(0,BarUtils.getStatusBarHeight(),0,0)
        initRefreshView()
        initRvAmount()
        showStateView()
    }

    override fun initListener() {
        //个人中心
        binding.imgUser.setOnClickListener {
            showPersonalDialog("CreditLimit Page")
            addEvent(EventType.CLICK.CLICK_USER,"CreditLimit Page")
        }
        //客服
        binding.imgKefu.setOnClickListener {
            showKefuDialog("CreditLimit Page")
            addEvent(EventType.CLICK.CLICK_CUSTOMER,"CreditLimit Page")
        }
        //完善流程
        binding.btnGetStarted.setOnClickListener {
            //上报
            TestDataLibInvoke.sycData()
            addEvent(EventType.CLICK.CLICK_CREDIT_LIMIT_ADD_INFORMATION,"")

            checkAllPermissions(false)
        }
        //申请贷款
        binding.btnCheck.setOnClickListener {
            //上报
            TestDataLibInvoke.sycData()
            addEvent(EventType.CLICK.CLICK_CREDIT_LIMIT_CHECK,"")

            checkAllPermissions(true)
        }
    }

    override fun initData() {
        loadLimitAction()
        loadAllPermissionsAction()
    }

    /* 初始化刷新 */
    private fun initRefreshView() {
        //禁止加载
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableAutoLoadMore(false)
        binding.refreshLayout.setOnRefreshListener {
            //发送刷新流程通知
            EventBus.getDefault().post(Configs.Event.PROCESS_REFRESH)

            loadLimitAction()
        }
        binding.refreshLayout.setOnLoadMoreListener {
            binding.refreshLayout.finishLoadMore()
        }
    }

    private fun initRvAmount(){
        binding.rvAmount.setHasFixedSize(true)
        binding.rvAmount.isNestedScrollingEnabled = false
        binding.rvAmount.isFocusableInTouchMode = false //不需要焦点
        val decoration = DensityUtils.dp2px(14f)
        binding.rvAmount.addItemDecoration(LinearDecoration(0,decoration,0,0))
        val layoutManager = LinearLayoutManager(getContext())
        layoutManager.orientation = RecyclerView.HORIZONTAL
        binding.rvAmount.layoutManager = layoutManager
        mAmountAdapter = AmountAdapter(binding.rvAmount)
        mAmountAdapter!!.setOnItemChildClickListener { parent, childView, position ->
            val item = this.mAmountAdapter!!.getItem(position)
        }
        binding.rvAmount.adapter = mAmountAdapter
    }

    /**
     * 显示样式
     */
    fun showStateView(){
        when(isComplete){
            true -> {//已完成 - 显示额度
                binding.processLayout.visibility = View.GONE
                binding.limitLayout.visibility = View.VISIBLE
                binding.successTipsLayout.visibility = View.VISIBLE
            }
            else -> {//未完成 - 显示完善资料
                binding.processLayout.visibility = View.VISIBLE
                binding.limitLayout.visibility = View.GONE
                binding.successTipsLayout.visibility = View.GONE
            }
        }
    }

    /**
     * 申请
     */
    private fun enterApply(){
        onIntent(ApplyActivity::class.java)
    }

    /**
     * 完善流程
     */
    private fun enterProcess(){
        onIntent(ProcessActivity::class.java)
    }

    /**
     * 设置显示额度
     */
    @SuppressLint("SetTextI18n")
    private fun showLimitData(data: JSONObject){
        val amountList = arrayListOf<String>()
        val amountString = data.optString("amount1")
        for (i in amountString.indices){
            amountList.add(amountString[i].toString())
        }
        mAmountAdapter!!.data = amountList
        binding.textSignAmount.text = "+" + data.optString("amount2")
        binding.textProfileAmount.text = "+" + data.optString("amount3")

        binding.textLimitAmount.text = data.optString("amount")
    }

    /**
     * 检查是否授权所有权限
     */
    private fun checkAllPermissions(isApply: Boolean){
        if (XXPermissions.isGranted(requireContext(),mPermissions!!)){
            if (isApply){
                enterApply()
            } else {
                enterProcess()
            }
        } else {
            XXPermissions.with(this)
                // 申请多个权限
                .permission(mPermissions)
                .request(object: OnPermissionCallback {
                    override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                        var permissionString = ""
                        permissions.forEach {
                            permissionString = "$permissionString$it,"
                        }
                        addEvent(EventType.CLICK.CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))

                        if (isApply){
                            enterApply()
                        } else {
                            enterProcess()
                        }
                    }
                    override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                        var permissionString = ""
                        permissions.forEach {
                            permissionString = "$permissionString$it,"
                        }
                        addEvent(EventType.CLICK.CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))

                        XXPermissions.startPermissionActivity(context!!,permissions)
                    }
                })
        }
    }

    /**
     * 获取贷款额度
     */
    private fun loadLimitAction(){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.LIMIT)
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                //需要显示的金额JSON
                var amountObject: JSONObject? = null
                //未完善资料之前，显示额度从启动页配置数据中取
                val commonData = getCommonObject()
                val customize = commonData.optJSONObject("customize")
                if (customize != null){
                    amountObject = customize.optJSONObject("loanLimit")
                }
                //后台没有配置loanLimit 默认额度
                if (amountObject == null){
                    amountObject = JSONObject()
                    amountObject.put("amount1","35000")
                    amountObject.put("amount2","15000")
                    amountObject.put("amount3","20000")

                }

                //完善资料之后显示的可申请金额需要从贷款额度接口中取 amount
                val limitArray = obj!!.optJSONArray("limit")
                if (limitArray != null && limitArray.length() > 0){
                    val limitObj = limitArray.optJSONObject(0)
                    amountObject.put("amount",limitObj.optString("amount"))
                }
                showLimitData(amountObject)
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                binding.refreshLayout.finishRefresh()
            }
        })
    }

    /**
     * 获取所有权限列表
     */
    private fun loadAllPermissionsAction() {
        if (mPermissions == null){
            mPermissions = arrayListOf()
        }
        mPermissions!!.clear()
        Thread{
            val commonData = getCommonObject()
            val customize = commonData.optJSONObject("customize")
            if(customize != null){
                val permissions = customize.optJSONObject("permissions")
                if (permissions != null){
                    val permission = permissions.optJSONArray("permission")
                    if (permission != null && permission.length() > 0){
                        for (i in 0..<permission.length()){
                            mPermissions!!.add(permission.optString(i))
                        }
                    }

                    val home = permissions.optJSONArray("home")
                    if (home != null && home.length() > 0){
                        for (i in 0..<home.length()){
                            mPermissions!!.add(home.optString(i))
                        }
                    }
                }
            }
        }.start()
    }

    override fun onStart() {
        super.onStart()
        addEvent(EventType.PAGE.PAGE_CREDIT_LIMIT_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(EventType.PAGE.PAGE_CREDIT_LIMIT_END,"")
    }
}